/*
 * Project: Sudoku Hint Engine for Android
 * Copyright (C) 2010-2013 Emanuel Moecklin
 * 
 * Available under the terms of the Lesser General Public License (LGPL)
 */
package com.onegravity.sudoku.solver.util;

import java.io.Serializable;
import java.util.BitSet;
import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * Iterator for the BitSet class
 * @author Emanuel Moecklin
 */
public class BitSetIterator<T> implements Iterator<Integer>, Serializable {

	private static final long serialVersionUID = -3712592362528255013L;
	
	private int min_pos;
	private int max_pos;
	private int pos; 
	private BitSet theBitSet;
	
	/**
	 * Use this constructor only in combination with restart(BitSet).
	 */
	public BitSetIterator() {}
	
	public BitSetIterator(BitSet bitset) {
		restart(bitset);
	}

	/**
	 * Restarts the Iterator with a new BitSet.
	 * This allows reuse of the objects for multiple BitSets (e.g. pencil marks for all cells)
	 * @param bitset
	 */
	public void restart(BitSet bitset) {
		min_pos = (bitset instanceof Potentials) ? 1 : 0;
		max_pos = (bitset instanceof Potentials) ? 9 : Integer.MAX_VALUE;
		pos = min_pos;
		theBitSet = bitset;
	}

	public boolean hasNext() {
		if (pos<min_pos || pos>max_pos || theBitSet==null) return false;
		int next = theBitSet.nextSetBit(pos);
		return next>=min_pos && next<=max_pos;
	}

	public Integer next() {
		if (theBitSet==null) return -1;
        pos = theBitSet.nextSetBit(pos);
        if (pos<min_pos) {
        	throw new NoSuchElementException();
        }
		return pos++;
	}

	public void remove() {}
}